/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.accident.controller;

import com.google.gson.Gson;
import com.koron.accident.domain.AccidentBulletin;
import com.koron.accident.service.api.AccidentBulletinService;
import com.koron.accident.util.BusinessCode;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.*;

@Api(tags = "accidentBulletin",description = "事故快报相关接口类")
@RestController
@RequestMapping("/accidentBulletin")
public class AccidentBulletinController {
    private final static Logger logger= LoggerFactory.getLogger(AccidentBulletinController.class);
    @Autowired
    private AccidentBulletinService accidentBulletinService;

    @Autowired
    private Util util;

    @ApiOperation(value = "保存事故快报")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id,新增不传，修改必传",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name", value = "事故名称",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentType", value = "事件类别",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "departmentCode", value = "事发单位code",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "departmentName", value = "事发单位名称",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "occurrencePlace", value = "发生地点",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "occurrenceTime", value = "发生时间",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentReason", value = "事故原因",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentDescription", value = "事故描述",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "isDeal", value = "是否发待办，0:不发送，1发送",  dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "dealPerson", value = "接收待办人员code，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "dealPersonName", value = "接收待办人员名称，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "isSendEmail", value = "是否发邮件，0:不发送，1发送",  dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "sendEmailPerson", value = "接收人email code，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sendEmailPersonName", value = "选择发送邮箱人员名称，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "isSendMsg", value = "是否发送短信，0:不发送，1发送",  dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "msgPerson", value = "接收短信人code,多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "msgPersonName", value = "接收短信人名称，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "msgContent", value = "短信内容",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "approver", value = "审批人", required = true, dataType = "String",paramType = "query")
    })
    @RequestMapping(value = "/save.htm",method = RequestMethod.POST)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String userCode,String approver, @ApiIgnore AccidentBulletin bean,
                                     @RequestParam(required = false)final String keepFiles, @RequestParam(required = false)final String delFiles,
                                     @RequestParam(required = false)final MultipartFile[]files){
        if (user==null){
            List<StaffBean> staffBeanList= (List<StaffBean>) util.staff(userCode,null).getData();
            if (null!=staffBeanList&&staffBeanList.size()>0)
                user=staffBeanList.get(0);
        }
        if (null==user){
            MessageBean<Integer> messageBean=new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        if (StringUtils.isNotEmpty(bean.getDealPerson())){
            String[] codes=bean.getDealPerson().split("[,，]");
            bean.setDealPerson(new Gson().toJson(Arrays.asList(codes)));
        }
        if (StringUtils.isNotEmpty(bean.getDealPersonName())){
            String[] names=bean.getDealPersonName().split("[,，]");
            bean.setDealPersonName(new Gson().toJson(Arrays.asList(names)));
        }
        if (StringUtils.isNotEmpty(bean.getSendEmailPerson())){
            String[] codes=bean.getSendEmailPerson().split("[,，]");
            bean.setSendEmailPerson(new Gson().toJson(Arrays.asList(codes)));
        }
        if (StringUtils.isNotEmpty(bean.getSendEmailPersonName())){
            String[] names=bean.getSendEmailPersonName().split("[,，]");
            bean.setSendEmailPersonName(new Gson().toJson(Arrays.asList(names)));
        }
        if (StringUtils.isNotEmpty(bean.getMsgPerson())){
            String[] codes=bean.getMsgPerson().split("[,，]");
            bean.setMsgPerson(new Gson().toJson(Arrays.asList(codes)));
        }
        if (StringUtils.isNotEmpty(bean.getMsgPersonName())){
            String[] names=bean.getMsgPersonName().split("[,，]");
            bean.setMsgPersonName(new Gson().toJson(Arrays.asList(names)));
        }
        bean.setUpdateTime(new Date());
        bean.setUpdateUser(user.getName());
        return accidentBulletinService.save(user,bean,approver,keepFiles,delFiles,files);
    }

    @ApiOperation("删除事故快报接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "事故id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "approver", value = "审批人", required = true, dataType = "String",paramType = "query")
    })
    @RequestMapping(value = "/delete.htm",method = RequestMethod.POST)
    public MessageBean<Integer> delete(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,String userCode,String approver,@RequestParam final String id){
        if (user==null){
            List<StaffBean> staffBeanList= (List<StaffBean>) util.staff(userCode,null).getData();
            if (null!=staffBeanList&&staffBeanList.size()>0)
                user=staffBeanList.get(0);
        }
        if (null==user){
            MessageBean<Integer> messageBean=new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return accidentBulletinService.delete(user,id,approver);
    }

    @ApiOperation("查询单个事故快报接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "事故id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/details.htm",method = RequestMethod.POST)
    public MessageBean<AccidentBulletin> details(@RequestParam final String id){
        return accidentBulletinService.queryOne(id);
    }

    @ApiOperation("事故快报列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "事件名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "departmentCode",value = "事发单位",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentType",value = "事故类型",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",required = true,dataType = "int",paramType = "query"),
    })
    @RequestMapping(value = "/list.htm",method = RequestMethod.POST)
    public MessageBean<DataBean<AccidentBulletin>> list(@RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String name, @RequestParam(required = false) final String departmentCode,
                                             @RequestParam(required = false) final String accidentType, @RequestParam Integer page, @RequestParam Integer pageSize){
        Integer start=null;
        if (page==null||page<=0){
            page=1;
            if (pageSize==null||pageSize<=0){
                pageSize=15;
            }
        }
        start=(page<=1)?0:(page-1)*pageSize;
        MessageBean<DataBean<AccidentBulletin>> msg= accidentBulletinService.queryByContion(corpCode,name,departmentCode,accidentType,start,pageSize);
        if (null!=msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("填写事故报告时--事故快报所有列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/queryAll.htm",method = RequestMethod.POST)
    public MessageBean<List<AccidentBulletin>> queryAll(@RequestParam(required = false) final String corpCode){
        return accidentBulletinService.queryAll(corpCode);
    }


    @ApiOperation("事故快报列表导出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "事件名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "departmentCode",value = "事发单位",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentType",value = "事故类型",dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/exportList.htm", method = RequestMethod.GET)
    public HttpEntity<?> exportList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String corpCode, @RequestParam(required = false) final String name, @RequestParam(required = false) final String departmentCode,
                                    @RequestParam(required = false) final String accidentType) {
        if (null == user) {
            return null;
        }
        List<AccidentBulletin> list = accidentBulletinService.exportList(user, corpCode, name,departmentCode,accidentType);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File targetFile = new File("static/excel/accidentBulletinList.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/accidentBulletinList.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("事故快报列表", targetFile, "accidentBulletinList.btl", map);
    }
}
